<?php
/**
 * Atlas KOTASOFT cakephp
 *
 * Bakes web interface 
 *
 * PHP versions 4 and 5
 *
 * ATLAS KOTASOFT  cakephp web code generator
 * Copyright 2009, Kotasoft agile factory, Inc. (http://www.atlascakephp.com)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009, Kotasoft agile factory , Inc. (http://www.kotasoft.com)
 * @link          http://www.atlascakephp.com  ATLAS KOTASOFT Project
 * @version       BETA 0.5 $
 * @modifiedby    $LastChangedBy: daniel castanera - guldoe and francisco dominguez - idioto $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

/* class KtinternationalitationsController, generate idioms */
class KtinternationalitationsController extends AppController {
 	 var $name = "Ktinternationalitations"; 
 	 var $ruta_admin = "/admin/ktinternationalitations/";
 	 var $__output="";
	 var $storage = array();
 	 
	 function admin_index() {
 	
 		$session=$this->Session->read(KT_SESSION); 
 	    $this->set("configuration",$session['Ktconfiguration']);  
		if(!$this->__dbConfig()){
       		$this->Session->setFlash('Your configuration is not available');
       		$this->log(__('Your configuration is not available',true), LOG_DEBUG);	
		}	 	
   		
  		include_once("../../cake/libs/l10n.php");		
 		$this->set('ruta_admin',$this->ruta_admin);
 		$this->L10n = new L10n();
 		
 		$this->selected_languages=array();
		$pretty_names=array();
		foreach($this->L10n->__l10nCatalog as $pretty)
			$pretty_names[]=$pretty["language"];

 		$vBug=array(0=>"");
		$pretty_names= array_merge($vBug,$pretty_names); 		
 						
		$this->set('languages',$pretty_names);
 		if(!empty($this->data))
 		{

 			$languages= array_keys($this->L10n->__l10nCatalog);
 			foreach($this->data["ktinternationalitations"] as $index=>$data)
 			{
 				if($data==1)
 					$this->selected_languages[]=$this->L10n->__l10nCatalog[$languages[$index-1]]["localeFallback"];
 			}
 			$this->__extract();
			
 		}
 	}
 	
	function __extract() {
		
		$response = '';
		$filename = '';

		$this->__oneFile=true;	//fran. estamos forzando que lo genere en un solo fichero
		$this->__filename = "default";	//fran. estamos forzando el nombre de fichero de salida
		$this->__extractTokens();
	}
	
	function __extractTokens() {
		
		$path=$_SESSION["kt_config"]["Ktconfiguration"]["directory"].DS."app".DS;
		$this->path=$path;
		$this->files = $this->__searchDirectory($path);

		foreach ($this->files as $file) 
		{
			$this->__file = $file;
			$code = file_get_contents($file);

			$this->__findVersion($code, $file);
			$allTokens = token_get_all($code);
			$this->__tokens = array();
			$lineNumber = 1;
			
			foreach ($allTokens as $token) {
				if ((!is_array($token)) || (($token[0] != T_WHITESPACE) && ($token[0] != T_INLINE_HTML))) {
					if (is_array($token)) {
						$token[] = $lineNumber;
					}
					$this->__tokens[] = $token;
				}

				if (is_array($token)) {
					$lineNumber += count(split("\n", $token[1])) - 1;
				} else {
					$lineNumber += count(split("\n", $token)) - 1;
				}
			}
			unset($allTokens);
			
			$this->basic();
			$this->basic('__c');
			$this->extended();
			$this->extended('__dc', 2);
			$this->extended('__n', 0, true);
			$this->extended('__dn', 2, true);
			$this->extended('__dcn', 4, true);
		}
		
		$this->__manageInfo();
		
	}	
	
	function __searchDirectory($path = null) {
		
		$files = glob("$path*.{php,ctp,thtml,inc,tpl}", GLOB_BRACE);
		$dirs = glob("$path*", GLOB_ONLYDIR);
	
		$files = $files ? $files : array();
		$dirs = $dirs ? $dirs : array();
		
		foreach ($dirs as $dir) {
			if (!preg_match("!(^|.+/)(CVS|.svn)$!", $dir)) {
				$files = array_merge($files, $this->__searchDirectory("$dir" . DS));
				if (($id = array_search($dir . DS . 'extract.php', $files)) !== FALSE) {
					unset($files[$id]);
				}
			}
		}
		return $files;
	}	
	
	
	function __findVersion($code, $file) {
		$header = '$Id' . ':';
		if (preg_match('/\\' . $header . ' [\\w.]* ([\\d]*)/', $code, $versionInfo)) {
			$version = str_replace(ROOT, '', 'Revision: ' . $versionInfo[1] . ' ' .$file);
			$this->__fileVersions[$file] = $version;
		}
	}	
	
	function basic($functionName = '__') {
		$count = 0;
		$tokenCount = count($this->__tokens);

		while (($tokenCount - $count) > 3) {
			list($countToken, $parenthesis, $middle, $right) = array($this->__tokens[$count], $this->__tokens[$count + 1], $this->__tokens[$count + 2], $this->__tokens[$count + 3]);
			if (!is_array($countToken)) {
				$count++;
				continue;
			}

			list($type, $string, $line) = $countToken;
			if (($type == T_STRING) && ($string == $functionName) && ($parenthesis == '(')) {

				if (in_array($right, array(')', ','))
					&& (is_array($middle) && ($middle[0] == T_CONSTANT_ENCAPSED_STRING))) {

					if ($this->__oneFile === true) {
							$this->__strings[$this->__formatString($middle[1])][$this->__file][] = $line;
					} else {
							$this->__strings[$this->__file][$this->__formatString($middle[1])][] = $line;
					}
				} /*else {
					//$this->__markerError($this->__file, $line, $functionName, $count);
				}*/
			}
			$count++;
		}
	}

	function extended($functionName = '__d', $shift = 0, $plural = false) {
		$count = 0;
		$tokenCount = count($this->__tokens);

		while (($tokenCount - $count) > 7) {
			list($countToken, $firstParenthesis) = array($this->__tokens[$count], $this->__tokens[$count + 1]);
			if (!is_array($countToken)) {
				$count++;
				continue;
			}

			list($type, $string, $line) = $countToken;
			if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
				$position = $count;
				$depth = 0;

				while ($depth == 0) {
					if ($this->__tokens[$position] == '(') {
						$depth++;
					} elseif ($this->__tokens[$position] == ')') {
						$depth--;
					}
					$position++;
				}

				if ($plural) {
					$end = $position + $shift + 7;

					if ($this->__tokens[$position + $shift + 5] === ')') {
						$end = $position + $shift + 5;
					}

					if (empty($shift)) {
						list($singular, $firstComma, $plural, $seoncdComma, $endParenthesis) = array($this->__tokens[$position], $this->__tokens[$position + 1], $this->__tokens[$position + 2], $this->__tokens[$position + 3], $this->__tokens[$end]);
						$condition = ($seoncdComma == ',');
					} else {
						list($domain, $firstComma, $singular, $seoncdComma, $plural, $comma3, $endParenthesis) = array($this->__tokens[$position], $this->__tokens[$position + 1], $this->__tokens[$position + 2], $this->__tokens[$position + 3], $this->__tokens[$position + 4], $this->__tokens[$position + 5], $this->__tokens[$end]);
						$condition = ($comma3 == ',');
					}
					$condition = $condition &&
						(is_array($singular) && ($singular[0] == T_CONSTANT_ENCAPSED_STRING)) &&
						(is_array($plural) && ($plural[0] == T_CONSTANT_ENCAPSED_STRING));
				} else {
					if ($this->__tokens[$position + $shift + 5] === ')') {
						$comma = $this->__tokens[$position + $shift + 3];
						$end = $position + $shift + 5;
					} else {
						$comma = null;
						$end = $position + $shift + 3;
					}

					list($domain, $firstComma, $text, $seoncdComma, $endParenthesis) = array($this->__tokens[$position], $this->__tokens[$position + 1], $this->__tokens[$position + 2], $comma, $this->__tokens[$end]);
					$condition = ($seoncdComma == ',' || $seoncdComma === null) &&
						(is_array($domain) && ($domain[0] == T_CONSTANT_ENCAPSED_STRING)) &&
						(is_array($text) && ($text[0] == T_CONSTANT_ENCAPSED_STRING));
				}

				if (($endParenthesis == ')') && $condition) {
					if ($this->__oneFile === true) {
						if ($plural) {
							$this->__strings[$this->__formatString($singular[1]) . "\0" . $this->__formatString($plural[1])][$this->__file][] = $line;
						} else {
							$this->__strings[$this->__formatString($text[1])][$this->__file][] = $line;
						}
					} else {
						if ($plural) {
							$this->__strings[$this->__file][$this->__formatString($singular[1]) . "\0" . $this->__formatString($plural[1])][] = $line;
						} else {
							$this->__strings[$this->__file][$this->__formatString($text[1])][] = $line;
						}
					}
				} else {
					$this->__markerError($this->__file, $line, $functionName, $count);
				}
			}
			$count++;
		}
	}	
	
	function beforeFilter(){     	 
    	if (!$this->Session->check('User') && 
    		isset($this->params['prefix']) && 
    		$this->params['prefix']=='admin') {
	   		
				$this->checkAdminSession();
		}
		$this->checkConfiguration();
			
    }
	
    
    function __buildFiles($filter="") {    	
		foreach ($this->__strings as $str => $fileInfo) {
			$output = '';
			$occured = $fileList = array();
			
			if ($this->__oneFile === true) {
				foreach ($fileInfo as $file => $lines) {
					$occured[] = "$file:" . join(';', $lines);

					if (isset($this->__fileVersions[$file])) {
						$fileList[] = $this->__fileVersions[$file];
					}
				}
				
				
				$occurances = join("\n#: ", $occured);
				$occurances = str_replace($this->path, '', $occurances);
				$output = "#: $occurances\n";
				$filename = $this->__filename;
				$valueAnt="";
				if (count($filter)>0 && isset($filter[$str])){
					$valueAnt=$filter[$str];
				}
				if (strpos($str, "\0") === false) {
						$output .= "msgid \"$str\"\n";
						$output .= "msgstr \"$valueAnt\"\n";
				} else {
						list($singular, $plural) = explode("\0", $str);
						$output .= "msgid \"$singular\"\n";
						$output .= "msgid_plural \"$plural\"\n";
						$output .= "msgstr[0] \"$valueAnt\"\n";
						$output .= "msgstr[1] \"$valueAnt\"\n";
				}
				
				$output .= "\n";
			} else {
				 
				foreach ($fileInfo as $file => $lines) {
					$filename = $str;
					$occured = array("$str:" . join(';', $lines));

					if (isset($this->__fileVersions[$str])) {
						$fileList[] = $this->__fileVersions[$str];
					}
					$occurances = join("\n#: ", $occured);
					$occurances = str_replace($this->path, '', $occurances);
					$output .= "#: $occurances\n";

					if (strpos($file, "\0") === false) {
						$output .= "msgid \"$file\"\n";
						$output .= "msgstr \"\"\n";
					} else {
						list($singular, $plural) = explode("\0", $file);
						$output .= "msgid \"$singular\"\n";
						$output .= "msgid_plural \"$plural\"\n";
						$output .= "msgstr[0] \"\"\n";
						$output .= "msgstr[1] \"\"\n";
					}
					$output .= "\n";
				}
			}
			
			$this->__store($filename, $output, $fileList);
			
		}
	
	
		//return $output; 
	}	
	
	function __writeFiles($language) {
		$output = $this->__store(0, 0, array(), 1);
		$output = $this->__mergeFiles($output);  
		foreach ($output as $file => $content) {
			$tmp = str_replace(array($this->path, '.php','.ctp','.thtml', '.inc','.tpl' ), '', $file);
			$tmp = str_replace(DS, '.', $tmp);
			$file = str_replace('.', '-', $tmp) .'.pot';
			$fileList = $content[1];
             
			unset($content[1]);

			$fileList = str_replace(array($this->path), '', $fileList);
             
			if (count($fileList) > 1) {
				$fileList = "Generated from files:\n#  " . join("\n#  ", $fileList);
			} elseif (count($fileList) == 1) {
				$fileList = 'Generated from file: ' . join('', $fileList);
			} else {
				$fileList = 'No version information was available in the source files.';
			}
			
				
			$file=$this->path."locale".DS.$language.DS."LC_MESSAGES".DS."default.po";	
			$fp = fopen($this->__output . $file, 'w');
			fwrite($fp, str_replace('--VERSIONS--', $fileList, join('', $content)));
			fclose($fp);
		}
	}	
    
   
	
	function __formatString($string) {
		$quote = substr($string, 0, 1);
		$string = substr($string, 1, -1);
		if ($quote == '"') {
			$string = stripcslashes($string);
		} else {
			$string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
		}
		$string = str_replace("\r\n", "\n", $string);
		return addcslashes($string, "\0..\37\\\"");
	}	
	
	function __store($file = 0, $input = 0, $fileList = array(), $get = 0) {
		//static $storage = array();
		

		if (!$get) {
			if (isset($this->storage[$file])) {
				$this->storage[$file][1] = array_unique(array_merge($this->storage[$file][1], $fileList));
				$this->storage[$file][] = $input;
			} else {
				$this->storage[$file] = array();
				$this->storage[$file][0] = $this->__writeHeader();
				$this->storage[$file][1] = $fileList;
				$this->storage[$file][2] = $input;
			}
		} else {
			 
			return $this->storage;
		}
	}
	
	function __writeHeader() {
		$output  = "# LANGUAGE translation of CakePHP Application\n";
		$output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
		$output .= "# --VERSIONS--\n";
		$output .= "#\n";
		$output .= "#, fuzzy\n";
		$output .= "msgid \"\"\n";
		$output .= "msgstr \"\"\n";
		$output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
		$output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
		$output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
		$output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
		$output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
		$output .= "\"MIME-Version: 1.0\\n\"\n";
		$output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
		$output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
		$output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
		return $output;
	}
	
	
	function __manageInfo(){
		
	
	    foreach($this->selected_languages as $language){
	    	if(!is_dir($this->path."locale")){	
	    				mkdir($this->path."locale");  
	    	}	
	    	
			if(!is_dir($this->path."locale".DS.$language)) {					
				mkdir($this->path."locale".DS.$language);
			}
			
			if(!is_dir($this->path."locale".DS.$language.DS."LC_MESSAGES")) {
				mkdir($this->path."locale".DS.$language.DS."LC_MESSAGES");	
			}
			
			$file=$this->path."locale".DS.$language.DS."LC_MESSAGES".DS."default.po";	
			
			$filterList="";
	        if (file_exists($file)){
				 $filterList = $this->__getMsgid($file);				
		 	}
		 	
			$this->__buildFiles($filterList);
		 	$this->__writeFiles($language);	
			$this->storage = array();
		}
		
	}
	
	// if file not empty we make merge else create new 
	
	
	
	function __generateFile($file=""){
		
		$listTokens = array();
		$loquesea="";
		
		if ($file!=""){			
			$listTokens = $this->__getMsgid($file);
			// comparar y generar la lista a devolver.			
		} 
		return $loquesea;
	}
	
	
	
	function __createFiles($file){
		$output = $this->__store(0, 0, array(), 1);
		$output = $this->__mergeFiles($output);
		
	}
	  
	function __mergeFiles($output) {
		foreach ($output as $file => $content) {
			if (count($content) <= 1 && $file != $this->__filename) {
				@$output[$this->__filename][1] = array_unique(array_merge($output[$this->__filename][1], $content[1]));

				if (!isset($output[$this->__filename][0])) {
					$output[$this->__filename][0] = $content[0];
				}
				unset($content[0]);
				unset($content[1]);

				foreach ($content as $msgid) {
					$output[$this->__filename][] = $msgid;
				}
				unset($output[$file]);
			}
		}
		return $output;
	}	
	
	function __getMsgid($file=""){
			
		$arrayResults =  array();
		$fichero = fopen($file,"r");
		
		// sacamos linea a linea y comparamos el fichero 
		while(!feof($fichero)){
             $linea = fgets($fichero,4096); 
            
             // msgid "The Role has been saved"
             $values= strstr($linea,"msgid");            
             
             if ($values!=""){
             	// limpiamos la cadena             	
             	$values = str_replace("msgid","",$values);
             	$values = ltrim($values);
             	$values = rtrim($values);             	
             	$values = str_replace("\"","",$values);
             	
             	//$arrayResults[$values]="";
             	
             	$nextLine = fgets($fichero,4096);
             	$valuesResult= strstr($nextLine,"msgstr");
             	if ($valuesResult!=""){    
             		$valuesResult = str_replace("msgstr","",$valuesResult);
             		$valuesResult = ltrim($valuesResult);
             		$valuesResult = rtrim($valuesResult);             	
             		$valuesResult = str_replace("\"","",$valuesResult);
             		$arrayResults[$values]=$valuesResult;
             	}
             } 
		} 
		fclose($fichero); 
		return $arrayResults;
	}
}
?>